/**
 * Month Picker 
 * @author Peter.Zheng
 * @version 1.0
 * @思路参考　website http://project.yctin.com/monthpicker
 *
 */
jQuery.fn.monthpicker = function(opts,callback) {
    if (typeof opts == "function") {
        opts.onChanged = opts;
    } else {
        if (typeof opts == "string") {
            var s = opts.split('-');
            opts = {
                elements: [{
                    tpl: 'year',
                    opt: {
                        value: parseInt(s[0])
                    }
                },{
                    tpl: 'month',
                    opt: {
                        value: parseInt(s[1])
                    }
                }],
                addTarget:this
            };
        }
        if (typeof callback == "function") {
            opts.onChanged = callback;
        }
    }
    opts = jQuery.extend({ //default
        elements: [{
            //选择年
            tpl: 'year'
        },{
            //选择月模板
            tpl: 'month'
        },{
            //选择季度模板
            tpl: 'quarter'
        }],
        addTarget:this,
        onChanged: false
    }, opts);

    var templates = jQuery.extend({
        //各类型模板默认数据
        year: {
            key: 'year',
            type: 'dropdown',
            caption: '请选择年份',
            range: '-11~0',
            value: new Date().getFullYear()
        },
        month: {
            key: 'month',
            type: 'button',
            caption: '请选择月份',
            text: ['01月', '02月', '03月', '04月', '05月', '06月', '07月', '08月', '09月', '10月', '11月', '12月'],
            range: '1~12',
            value: new Date().getMonth() + 1
        },
        quarter: {
            key: 'quarter',
            type: 'quarter',
            caption: '请选择季度',
            text: ['第1季度', '第2季度', '第3季度', '第4季度'],
            range: '1~4',
            value: 1
        }
    }, opts.templates);

    return this.each( function() {
        if($("#J_yearMonth_picker").size()>0) {
            $("#J_yearMonth_picker").remove();
        }
        var $container=$("<div id='J_yearMonth_picker' class='app_widgets_pos'></div>")
        var $body = jQuery('<div class="bd_in"></div>');
        var currentValue = {};
        var $_prev;
        var $_next;
        var $_picker_mask;
        var $_inputTarget;
        var $_clear;
        var $_close;
        for(var i = 0; i < opts.elements.length; i++) {
            add(opts.elements[i]);
        }
            //无结构则添加
            jQuery('<div class="ace_widgets_mod ace_widgets_monthPicker app_radius_3 w_240"></div>').append($body).appendTo($container.html(""));
            $container.appendTo($("body"));
            $_picker_mask=$container;
            $_inputTarget=$(opts.addTarget);
            $_clear=$_picker_mask.find(".J_yearMonth_clear").eq(0);
            $_close=$_picker_mask.find(".J_yearMonth_close").eq(0);
      
        //添加关闭事件，与清空事件
        //显示，并放在正确的位置
        _setPos($_inputTarget,$_picker_mask);
        function _close(){
           $_picker_mask.fadeOut("fast",function(){
               $(this).remove();
           })
        };
        function _clear(){
            if($_inputTarget[0].tagName.toUpperCase()=="INPUT") {
                        $_inputTarget.val("");
                    } else {
                        $(opts.addTarget).empty();
                    }
             };
        $_clear.click(function(){
           _clear();
        });
        $_close.click(function(){
            _close();
        });
        return this;
        //设置弹层的位置
        function _setPos($_Target,$_Mask){
             var pos={};
             pos._l=$_Target.offset().left;
             pos._t=$_Target.offset().top;
             pos._h=$_Target.outerHeight();
             $_picker_mask.css({
                 left:pos._l,
                 top:pos._t+pos._h
             });
        }
        function toArray(str,cur) {
            if (str.indexOf('~') == -1) {
                return [cur];
            }

            var sY,eY,y=str.split("~");

            if (y[0].charAt(0) == '-' || y[1].charAt(0) == '+') {
                sY = cur + parseInt(y[0], 10);
                eY = cur + parseInt(y[1], 10);
            } else if (y[0].match(/^\d*$/) && y[1].match(/^\d*$/)) {
                sY = parseInt(y[0], 10);
                eY = parseInt(y[1], 10);
            } else {
                return [cur];
            }

            var p=0, o=new Array;
            for (var i = sY; i <= eY; i++) {
                o[p++]=i;
            }
            return o;
        }

        function add(element) {
            eval("var tpl = templates." + (element.tpl));
            if (!tpl) {
                return false;
            }
            tpl = jQuery.extend(tpl, element.opt);
            set(tpl.key,tpl.value);
            var range = toArray(tpl.range,tpl.value);
            var text = (tpl.text || range);
            var className = '';
            function _addRange(range) {
                //先清空ul里的li
                $items.empty();
                for (var i = 0; i < range.length; i++) {
                    //默认指定就选中
                    className = (tpl.value == range[i]) ? "selected app_radius_3" : "app_radius_3";
                    jQuery('<li></li>').append(
                    jQuery('<a href="javascript:;" title="' + range[i] + '" class="' + className + '">' + text[i] +'年</a>').click( function() {
                        var $this = jQuery(this);
                        var value = $this.attr('title');
                        var $menu = $this.parent().parent();
                        //$menu.slideUp(0).show(1).parent().find('.selected:first').html(value);
                        var _text=parseInt($(this).text(),10);
                        if($(opts.addTarget)[0].tagName.toUpperCase()=="INPUT") {
                            $(opts.addTarget).val(_text);
                        } else {
                            $(opts.addTarget).html(_text);
                        }
                        $menu.find('a').removeClass('selected');
                        $this.addClass('selected');
                        update(tpl.key,value,this);
                        //点击关闭图层
                        $_picker_mask.hide();
                    })
                    ).appendTo($items);
                }
            };

            if (tpl.type == "dropdown") {
                var $list = jQuery('<div class="hd tac"><a href="javascript:void(0)" title="向上翻" class="widgets_icon_larrow icon prev">&nbsp;</a><span class="select_title">'+tpl.caption+'</span><a href="javascript:void(0)" title="向下翻" class="widgets_icon_rarrow icon next">&nbsp;</a></div><div class="bd"><ul class="option_list c"></ul></div><div class="fd"><a href="javascript:void(0)" class="a_blue_d J_yearMonth_clear" title="[清空]" class="J_yearMonth_clear">[清空]</a><a href="javascript:void(0)" class="a_blue_d J_yearMonth_close"  title="[关闭]" class="J_yearMonth_close">[关闭]</a></div>');
                var $items = $list.find('ul.option_list');
                _addRange(range);
                $body.append($list);
                $_prev=$list.find(".prev").eq(0);
                $_next=$list.find(".next").eq(0);
                //click 左边btn
                $_prev.click( function() {
                    tpl.range='-11~0';
                    //往后12年
                    tpl.value=tpl.value-12;
                    //范围
                    range = toArray(tpl.range,tpl.value);
                    //年文字
                    text = (tpl.text || range);
                    _addRange(range);
                });
                //click 右边btn
                var _first=true;
                $_next.click( function() {
                    tpl.range='-11~0';
                    tpl.value+=12;
                    range = toArray(tpl.range,tpl.value);
                    text = range;
                    _addRange(range);
                });
            } else if (tpl.type == "button") {
                var $items = jQuery('<div class="hd tac"><span class="select_title">'+tpl.caption+'</span></div><div class="bd"><ul class="option_list c"></ul></div><div class="fd"><a href="javascript:void(0)" class="a_blue_d J_yearMonth_clear" title="[清空]" class="J_yearMonth_clear">[清空]</a><a href="javascript:void(0)" class="a_blue_d J_yearMonth_close"  title="[关闭]" class="J_yearMonth_close">[关闭]</a></div>');
                var $_ul=$items.find("ul").eq(0);
                tpl.value=new Date().getMonth() + 1;
                for (var i = 0; i < range.length; i++) {
                    className = (tpl.value == range[i]) ? "selected app_radius_3" : "app_radius_3";
                    jQuery('<li><a href="javascript:void(0);" title="' + range[i] + '" class="'+ className +'">'+ text[i] + '</a></li>').click( function() {
                        var $this = jQuery(this).find("a").eq(0);
                        var value = $this.attr('title');
                        $this.removeClass('selected');
                         var _text=parseInt($(this).text(),10);
                        if($(opts.addTarget)[0].tagName.toUpperCase()=="INPUT") {
                            $(opts.addTarget).val(_text);
                        } else {
                            $(opts.addTarget).html(_text);
                        }
                        update(tpl.key,value,this);
                        //点击关闭图层
                        $_picker_mask.hide();
                    }).appendTo($_ul);
                };
                $body.append($items);
            }else if(tpl.type == "quarter"){
                  var $items = jQuery('<div class="hd tac"><span class="select_title">'+tpl.caption+'</span></div><div class="bd"><ul class="option_list c"></ul></div><div class="fd"><a href="javascript:void(0)" class="a_blue_d J_yearMonth_clear" title="[清空]" class="J_yearMonth_clear">[清空]</a><a href="javascript:void(0)" class="a_blue_d J_yearMonth_close"  title="[关闭]" class="J_yearMonth_close">[关闭]</a></div>');
                   var $_ul=$items.find("ul").eq(0);
               for (var i = 0; i < range.length; i++) {
                    className = (tpl.value == range[i]) ? "selected app_radius_3" : "app_radius_3";
                    jQuery('<li><a href="javascript:void(0);" title="' + range[i] + '" class="'+ className +'">'+ text[i] + '</a></li>').click( function() {
                        var $this = jQuery(this).find("a").eq(0);
                        var value = $this.attr('title');
                        $this.removeClass('selected');
                         var _text=$(this).text();
                         _text=_text.replace(/\D/g,"");
                        if($(opts.addTarget)[0].tagName.toUpperCase()=="INPUT") {
                            $(opts.addTarget).val(_text);
                        } else {
                            $(opts.addTarget).html(_text);
                        }
                        update(tpl.key,value,this);
                        //点击关闭图层
                        $_picker_mask.hide();
                    }).appendTo($_ul);
                };
                $body.append($items);
            }
        }

        function set(key,value) {
            eval("currentValue." + key + "=" + value+ ";");
        }

        function update(key,value,$obj) {
            set(key,value);
            if (typeof opts.onChanged == "function") {
                opts.onChanged(currentValue,$container);
            }
        }

    });
};